const express = require('express');
const multer = require('multer');
const fs = require('fs-extra');
const path = require('path');
const cors = require('cors'); // 引入cors中间件

const app = express();
const port = 3000;

app.use(cors()); // 使用cors中间件
// 新增：添加JSON body解析中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const upload = multer();

// 上传分片
app.post('/upload/chunk', upload.single('file'), async (req, res) => {
  const { index, uploadId, fileName } = req.body;
  const chunkDir = path.join(__dirname, 'uploads', uploadId);
  await fs.ensureDir(chunkDir);
  const chunkPath = path.join(chunkDir, `${fileName}-${index}`);
  await fs.writeFile(chunkPath, req.file.buffer);
  res.status(200).send('分片上传成功');
});

app.get('/upload/chunks', async (req, res) => {
  const { uploadId, fileName } = req.query;
  const chunkDir = path.join(__dirname, 'uploads', uploadId);
  try {
    const chunks = await fs.readdir(chunkDir);
    const uploadedIndices = chunks
      .filter(file => file.startsWith(`${fileName}-`))
      .map(file => parseInt(file.split('-')[1]));
    res.json({ uploadedIndices });
  } catch (err) {
    if (err.code === 'ENOENT') {
      res.json({ uploadedIndices: [] });
    } else {
      res.status(500).send('获取分片信息失败');
    }
  }
});

// 在合并分片路由前添加multer处理中间件
app.post('/upload/merge', upload.none(), async (req, res) => {
    const { uploadId, fileName } = req.body;
    console.log('uploadId, fileName :', uploadId, fileName);
    const chunkDir = path.join(__dirname, 'uploads', uploadId);
    const chunks = await fs.readdir(chunkDir);
    chunks.sort((a, b) => {
      const indexA = parseInt(a.split('-')[1]);
      const indexB = parseInt(b.split('-')[1]);
      return indexA - indexB;
    });

    const targetPath = path.join(__dirname, 'uploads', fileName);
    const writeStream = fs.createWriteStream(targetPath);

    for (const chunk of chunks) {
      const chunkPath = path.join(chunkDir, chunk);
      const readStream = fs.createReadStream(chunkPath);
      await new Promise((resolve, reject) => {
        readStream.pipe(writeStream, { end: false });
        readStream.on('end', resolve);
        readStream.on('error', reject);
      });
      await fs.remove(chunkPath);
    }
    await fs.remove(chunkDir);
    res.status(200).send('文件合并成功');
});

app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
});